﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Xml.Serialization;
using VO.Business.Controllers;
using VO.Entities;

namespace VO.RestService
{
    // Start the service and browse to http://<machine_name>:<port>/tracks/help to view the service's generated help page
    // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
    // a single instance of the service to process all calls.	
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    // NOTE: If the service is renamed, remember to update the global.asax.cs file

    public class TracksService : ITracksService
    {
        // TODO: Implement the collection resource that will contain the SampleItem instances

        
        [WebGet(UriTemplate = "")]
        public List<Track> GetTracks()
        {
            return TracksController.GetTracks(); ;
        }

        [WebInvoke(UriTemplate = "", Method = "POST")]
        public Track Create(Track instance)
        {
            // TODO: Add the new instance of SampleItem to the collection
            TracksController.SaveTrack(instance, true);
            return instance;
        }

        [WebGet(UriTemplate = "/{id}")]
        public Track Get(string id)
        {
            return TracksController.GetTrack(new Guid(id));
        }

        [WebInvoke(UriTemplate = "/{id}", Method = "PUT")]
        public Track Update(string id, Track instance)
        {
            TracksController.SaveTrack(instance, false);
            return instance;
        }

        [WebInvoke(UriTemplate = "/{id}", Method = "DELETE")]
        public void Delete(string id)
        {
            TracksController.DeleteTrack(new Guid(id));
        }


        #region helpers serialization
        internal static void WriteToFile<T>(T obj, string filePath)
        {
            using (FileStream file = new FileStream(filePath, FileMode.Create))
            {
                (new BinaryFormatter()).Serialize(file, obj);
            }
        }

        internal static T ReadFromFile<T>(string filePath)
        {
            using (FileStream file = new FileStream(filePath, FileMode.Open))
            {
                return (T)(new BinaryFormatter()).Deserialize(file);
            }
        }
        #endregion

    }
}
